package com.yoyo.yyadsdk.main;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

import com.anye.greendao.gen.AppEntityDao;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.LocalTimingEntityDao;
import com.dollkey.hdownload.activity.AdWebViewActivity;
import com.yoyo.ad.utils.StringUtil;
import com.yoyo.yyadsdk.activity.EmptyActivity;
import com.yoyo.yyadsdk.bean.dao.AppEntity;
import com.yoyo.yyadsdk.bean.dao.LocalShortcutEntity;
import com.yoyo.yyadsdk.bean.dao.LocalTimingEntity;
import com.yoyo.yyadsdk.bean.dao.PullEntity;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.demo.DBManager;
import com.yoyo.yyadsdk.serv.AddShortCutService;
import com.yoyo.yyadsdk.serv.UpdateDataService;
import com.yoyo.yyadsdk.util.ActivityUtils;
import com.yoyo.yyadsdk.util.GreenDaoManager;
import com.yoyo.yyadsdk.util.PullUtils;
import com.yoyo.yyadsdk.util.ShortcutUtil;
import com.yoyo.yyadsdk.util.TimeUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TimingService extends Service {

    private Timer mTimer;
    private Context mContext;
    private TimerTask mTimerTask;
    private LocalTimingEntityDao mLocalTimingEntityDao;
    private final long period = TimeUtils.MINUTE;
    private String name;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        mLocalTimingEntityDao = GreenDaoManager.getInstance().getDaoSession().getLocalTimingEntityDao();
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                List<LocalTimingEntity> list = mLocalTimingEntityDao.queryBuilder().where(
                        LocalTimingEntityDao.Properties.Time.lt(System.currentTimeMillis()),
                        LocalTimingEntityDao.Properties.Time.ge(System.currentTimeMillis() - period))
                        .orderAsc(LocalTimingEntityDao.Properties.Time).list();

                for (LocalTimingEntity localTimingEntity : list) {
                    switch (localTimingEntity.getType()) {
                        case PullFeature.ALARM_MONITOR_TIME_AUTO_PULL:
                            List<PullEntity> pullEntities = PullUtils.getPullEntities(PullFeature.PULL_AUTO);
                            for (final PullEntity p : pullEntities) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        EmptyActivity.launch(mContext, PullFeature.PULL_AUTO, p);
                                    }
                                }, 200);
                            }
                            break;
                        case PullFeature.ALARM_MONITOR_TIME_KILL:
                            DaoSession daoSession = GreenDaoManager.getInstance().getDaoSession();
                            List<AppEntity> killList = daoSession.getAppEntityDao().queryBuilder().
                                    where(AppEntityDao.Properties.IsCloseApp.eq(true)).list();
                            for (AppEntity a : killList) {
                                if (ActivityUtils.appIsRunning(mContext, a.getTPkg()) && !ActivityUtils.isAppOnForeground(mContext, a.getTPkg())) {
                                    ActivityUtils.killBackgroundProcesses(mContext, a.getTPkg());
                                }
                            }
                            break;
                        case PullFeature.ALARM_UPDATE_DATA:
//                            startService(new Intent(mContext, UpdateDataService.class));
                            UpdateDataService.getInstance(mContext);
                            break;
                        case PullFeature.ALARM_SHORT_CUT:
                            startService(new Intent(mContext, AddShortCutService.class));
                            break;
                        case PullFeature.ALARM_DEL_SHORT_CUT:
                            String[] params = localTimingEntity.getParam().split(",");
                            int shortcutCount = getShortcutCount(mContext, params[0]);
                            if (shortcutCount > 0) {
                                ShortcutUtil.deleteShortCut(mContext, AdWebViewActivity.class.getName(), params[0]);
//                            ShortcutUtil.deleteShortCut(mContext, "com.yoyo.shortcut" + params[1], params[0]);
                            }
                            LocalShortcutEntity localShortcutEntity = DBManager.getLocalShortcutEntity(Integer.parseInt(params[1]));
                            if (localShortcutEntity != null) {
                                localShortcutEntity.setIsDel(true);
                                DBManager.saveLocalShortcutEntity(localShortcutEntity);
                            }
                            break;
                        case PullFeature.ALARM_MONITOR_TIME_ALIVE:
                            //拉活后，清除存活超时的
                            String packageName = localTimingEntity.getParam();
                            if (ActivityUtils.appIsRunning(mContext, packageName) && !ActivityUtils.isAppOnForeground(mContext, packageName)) {
                                ActivityUtils.killBackgroundProcesses(mContext, packageName);
                            }
                            break;
                    }
                    if (localTimingEntity.getLoop()) {
                        localTimingEntity.setTime(localTimingEntity.getTime() + localTimingEntity.getPeriod());
                        mLocalTimingEntityDao.insertOrReplace(localTimingEntity);
                    } else {
                        mLocalTimingEntityDao.delete(localTimingEntity);
                    }
                }
            }
        };
        mTimer.schedule(mTimerTask, 0, period);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int getShortcutCount(Context context, String title) {
        int count = 0;
//        String title = "支付宝";
        getHomePackageName(context);
        String uri = Build.VERSION.SDK_INT < 19 ? "content://com.android.launcher2.settings/favorites?notify=true"
                : "content://com.android.launcher3.settings/favorites?notify=true";
        String uriStr = StringUtil.isNull(name) ? uri : "content://".concat(name).concat(".settings/favorites?notify=true");
        final Uri CONTENT_URI = Uri.parse(uriStr);
//        final Cursor c = context.getContentResolver().query(CONTENT_URI, null, null, null, null);
        final Cursor c = context.getContentResolver().query(CONTENT_URI, null, "title=?", new String[]{title}, null);
        if (c != null) {
            if (c.getCount() > 0)
                count = c.getCount();
            c.close();
        }
        return count;
    }

    private void getHomePackageName(Context context) {
        if (name == null) {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo ri : resolveInfo) {
                if (ri.activityInfo.packageName.contains("launcher")) {
                    name = ri.activityInfo.packageName;
                }
            }
        }
    }
}
